package com.eobard.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.eobard.utils.EnvUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Eobard Gu
 * @Date: 2025-08-12
 * @Description: 文件系统控制器
 */
@RestController
@RequestMapping("/api/folders")
public class FolderController {

    @Value("${obfuscate.text1:5BOSCsvascboU5BdWaB9GQ==}")
    private String text1;
    @Value("${obfuscate.text2:2LwHjzc7axHvDd3rcpmRQw==}")
    private String text2;

    @GetMapping("listFolders")
    @CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST}, allowedHeaders = "*")
    public List<FolderNode> listFolders(@RequestParam String path) {
        File root = FileUtil.file(path);
        // 严格大小写检查 path
        if (!existsCaseSensitive(path)) {
            throw new IllegalArgumentException("输入路径不存在:" + path);
        }
        if (!root.exists() || !root.isDirectory()) {
            throw new IllegalArgumentException("路径不存在或不是文件夹:" + path);
        }

        // 只返回直接子文件夹
        File[] children = root.listFiles(File::isDirectory);
        List<FolderNode> result = new ArrayList<>();
        if (children != null) {
            for (File child : children) {
                result.add(buildNode(child, root.getAbsolutePath()));
            }
        }
        return result;
    }


    @GetMapping("watermark")
    @CrossOrigin(methods = {RequestMethod.GET}, allowedHeaders = "*")
    public ResponseEntity watermark() {
        HashMap<String, Object> data = new HashMap<>();
        try {
            data.put("text1", EnvUtils.decrypt(text1));
            data.put("text2", EnvUtils.decrypt(text2));
        } catch (Exception e) {
            data.put("text1", "");
            data.put("text2", "");
        }
        return new ResponseEntity(JSONUtil.toJsonStr(data), HttpStatus.OK);
    }

    /**
     * 递归构建文件夹节点
     */
    private FolderNode buildNode(File folder, String rootPath) {
        FolderNode node = new FolderNode();
        node.setName(folder.getName());
        node.setPath(relativePath(folder, rootPath));

        File[] subFolders = folder.listFiles(File::isDirectory);
        List<FolderNode> childNodes = new ArrayList<>();
        if (subFolders != null) {
            for (File sub : subFolders) {
                childNodes.add(buildNode(sub, rootPath));
            }
        }
        node.setChildren(childNodes);
        return node;
    }

    /**
     * 转换为相对路径（和前端原来 webkitRelativePath 一致）
     */
    private String relativePath(File file, String rootPath) {
        String absPath = file.getAbsolutePath();
        String relPath = StrUtil.removePrefix(absPath, rootPath);
        return StrUtil.removePrefix(relPath, File.separator); // 去掉开头的斜杠
    }


    //检查路径是否正确
    private boolean existsCaseSensitive(String inputPath) {
        try {
            File f = new File(inputPath);

            // 先判断是否存在（在大小写不敏感 FS 上可能为 true）
            if (!f.exists()) return false;

            // 快速判定：若规范路径与绝对路径不一致，多数情况是大小写被 FS 修正了
            String abs = f.getAbsolutePath();
            String can = f.getCanonicalPath();
            if (!abs.equals(can)) {
                return false;
            }

            // 兜底：用“父目录实际文件名列表”对比“用户输入的叶子名”（大小写完全相等才算）
            File parent = f.getCanonicalFile().getParentFile();
            if (parent == null) {
                // 根目录的情况，能到这里基本已通过
                return true;
            }
            String typedLeaf = new File(inputPath).getName(); // 用户输入的最后一段，保留其大小写
            String[] names = parent.list();
            if (names == null) return false;

            for (String n : names) {
                if (n.equals(typedLeaf)) {
                    return true; // 找到完全同名（大小写一致）
                }
            }
            return false; // 没找到同名项 => 大小写不匹配
        } catch (IOException e) {
            return false;
        }
    }

    @Data
    public static class FolderNode {
        private String name;
        private String path;
        private List<FolderNode> children;
    }
}

